package database

import (
	"errors"
	"fmt"
	"gorm.io/gorm/clause"
)

type User struct {
	Name     string `json:"name" `
	Password string `json:"password"`
	Status   string `json:"status"`
	Id       string `json:"id" gorm:"primaryKey"`
}

func (user User) TableName() string {
	return "user"
}

// Login 登录
func Login(u *User) User {
	db, err := GetDBInstance()
	if err != nil {
		panic(err)
	}
	var user User
	db.Where("name = ? and password = ?", (*u).Name, (*u).Password).First(&user)
	return user
}

// LogOff 注销
func LogOff(user *User) error {
	db, err := GetDBInstance()
	if err != nil {
		return err
	}
	var users []User
	result := db.Table("user").Clauses(clause.Returning{}).Where(
		"name = ? and password = ? and id = ?",
		user.Name,
		user.Password,
		user.Id,
	).Delete(&users)
	fmt.Println(users)
	if result.Error != nil {
		return result.Error
	} else if result.RowsAffected > 0 {
		return nil
	} else {
		return errors.New("该用户不存在，请重试！")
	}
}
